package com.sqly.doc.menu.fwjh;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ihidea.multilinechooselib.MultiLineChooseLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePlan;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.CustomDatePicker;
import com.sqly.doc.view.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import cxy.com.validate.IValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.ValidateAnimation;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.MaxLength;
import cxy.com.validate.annotation.NotNull;
import cz.msebera.android.httpclient.Header;

public class fwjh_add extends MyBaseActivity {
    @Index(1)
    @NotNull(msg = "计划时间不能为空")
    @Bind(R.id.jhsj)
    EditText jhsj;

    @Index(2)
    @Bind(R.id.bz)
    @MaxLength(length = 20, msg = "最大长度为20个字符")
    EditText bz;

    @Index(3)
    @Bind(R.id.fwnr_qt)
    @MaxLength(length = 20, msg = "服务内容其他最大长度为20个字符")
    EditText fwnr_qt;

    @Bind(R.id.qysj)
    TextView qysj;

    MultiLineChooseLayout fwnr;//服务内容
    private List<String> fwnrData = new ArrayList<>();
    private CustomDatePicker customDatePicker;
    Context con = fwjh_add.this;
    //标题
    TextView title, uname;
    ServicePlan obj;
    String url = "";
    String signupid = "", signuptime="";
    LinearLayout nr_qt_ll;
    LinearLayout back;

    @Override
    protected void initUI() {
        setContentView(R.layout.fwjh_add);
        ButterKnife.bind(this);
        Validate.reg(this);
        signupid = getIntent().getStringExtra("signupid");
        signuptime=getIntent().getStringExtra("signuptime");
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (ServicePlan) getIntent().getExtras().getSerializable("b");
            url = HttpUrl.EditFwjh;
        } else {
            url = HttpUrl.AddFwjh;
            obj = new ServicePlan();
        }
        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void init() {
        nr_qt_ll = (LinearLayout) findViewById(R.id.nr_qt_ll) ;
        //fwnr_qt = (EditText) findViewById(R.id.fwnr_qt);
        if (obj != null && !StringUtils.isEmpty(obj.getService_content_qt())) {
            fwnr_qt.setText(obj.getService_content_qt());
        }
        //bz = (EditText) findViewById(R.id.bz);
        if (obj != null && !StringUtils.isEmpty(obj.getRemarks())) {
            bz.setText(obj.getRemarks());
        }
        qysj.setText(signuptime);
        //jhsj = (EditText) findViewById(R.id.jhsj);
        if (obj != null && !StringUtils.isEmpty(obj.getPlan_time())) {
            jhsj.setText(DateConvert.dateToString(DateConvert.toDate(obj.getPlan_time(), DateConvert.YMD), DateConvert.YMD)+"");
        }
        final String minJhsj = DateConvert.dateToString(DateConvert.toDate(signuptime, DateConvert.YMDHM), DateConvert.YMDHM);
        jhsj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        jhsj.setText(time.split(" ")[0]);
                    }
                }, minJhsj, DateConvert.getCustomDatePickerEndRq()); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                if (obj != null && !StringUtils.isEmpty(obj.getPlan_time())) {
                    customDatePicker.show(DateConvert.dateToString(DateConvert.toDate(obj.getPlan_time(), DateConvert.YMD), DateConvert.YMD));
                }else {
                    customDatePicker.show(minJhsj);
                }
            }
        });
        fwnr = (MultiLineChooseLayout) findViewById(R.id.fwnr);
        fwnrData.add("一般体格检查");
        fwnrData.add("测血糖");
        fwnrData.add("测血压");
        fwnrData.add("中医药服务");
        fwnrData.add("血常规");
        fwnrData.add("尿常规");
        fwnrData.add("肝功能");
        fwnrData.add("肾功能");
        fwnrData.add("血脂");
        fwnrData.add("心电图");
        fwnrData.add("彩超");
        fwnrData.add("转诊");
        fwnrData.add("会诊");
        fwnrData.add("其他");
        fwnr.setList(fwnrData);

        if (obj != null && !StringUtils.isEmpty(obj.getService_content())) {
            if (obj.getService_content().contains(",")) {
                String[] ss = obj.getService_content().split(",");
                for (int i = 0; i < ss.length; i++) {
                    if (!StringUtils.isEmpty(ss[i])) {
                        if(Integer.parseInt(ss[i])==0){
                            fwnr.setIndexItemSelected(Integer.parseInt(ss[i]));
                        }else{
                            fwnr.setIndexItemSelected(Integer.parseInt(ss[i])-1);
                        }
                        if(Integer.parseInt(ss[i])==14){
                            nr_qt_ll.setVisibility(View.VISIBLE);
                        }
                    }
                }
            } else {
                if(Integer.parseInt(obj.getService_content())==0){
                    fwnr.setIndexItemSelected(Integer.parseInt(obj.getService_content()));
                }else{
                    fwnr.setIndexItemSelected(Integer.parseInt(obj.getService_content())-1);
                }
                if(Integer.parseInt(obj.getService_content())==14){
                    nr_qt_ll.setVisibility(View.VISIBLE);
                }
            }
        }else{
            fwnr.setIndexItemSelected(0);
        }
        //单选
        fwnr.setOnItemClickListener(new MultiLineChooseLayout.onItemClickListener() {
            @Override
            public void onItemClick(int position, String text) {
               if("其他".equals(text) && nr_qt_ll.getVisibility() == View.GONE){
                   nr_qt_ll.setVisibility(View.VISIBLE);
               }else if("其他".equals(text) && nr_qt_ll.getVisibility() == View.VISIBLE){
                   nr_qt_ll.setVisibility(View.GONE);
                   fwnr_qt.setText("");
               }
            }
        });
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("服务计划");
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<Integer> nrlist = fwnr.getAllItemSelectedIndex();
                String fwnrStrs = "", fwnrNameStrs = "";
                for (int i = 0; i < nrlist.size(); i++) {
                    fwnrStrs = fwnrStrs + "," + (nrlist.get(i) + 1);
                    Integer wz = nrlist.get(i);
                    if(wz == 0) {
                        fwnrNameStrs = fwnrNameStrs + "," + "一般体格检查";
                    }else if(wz == 1) {
                        fwnrNameStrs = fwnrNameStrs + "," + "测血糖";
                    }else if(wz == 2) {
                        fwnrNameStrs = fwnrNameStrs + "," + "测血压";
                    }else if(wz == 3) {
                        fwnrNameStrs = fwnrNameStrs + "," + "中医药服务";
                    }else if(wz == 4) {
                        fwnrNameStrs = fwnrNameStrs + "," + "血常规";
                    }else if(wz == 5) {
                        fwnrNameStrs = fwnrNameStrs + "," + "尿常规";
                    }else if(wz == 6) {
                        fwnrNameStrs = fwnrNameStrs + "," + "肝功能";
                    }else if(wz == 7) {
                        fwnrNameStrs = fwnrNameStrs + "," + "肾功能";
                    }else if(wz == 8) {
                        fwnrNameStrs = fwnrNameStrs + "," + "血脂";
                    }else if(wz == 9) {
                        fwnrNameStrs = fwnrNameStrs + "," + "心电图";
                    }else if(wz == 10) {
                        fwnrNameStrs = fwnrNameStrs + "," + "彩超";
                    }else if(wz == 11) {
                        fwnrNameStrs = fwnrNameStrs + "," + "转诊";
                    }else if(wz == 12) {
                        fwnrNameStrs = fwnrNameStrs + "," + "会诊";
                    }else if(wz == 13) {
                        fwnrNameStrs = fwnrNameStrs + "," + "其他";
                    }
                }
                if(null != fwnrStrs && !"".equals(fwnrStrs) &&  fwnrStrs.startsWith(",")){
                    fwnrStrs = fwnrStrs.substring(1,fwnrStrs.length());
                }
                if(null != fwnrNameStrs && !"".equals(fwnrNameStrs) &&  fwnrNameStrs.startsWith(",")){
                    fwnrNameStrs = fwnrNameStrs.substring(1,fwnrNameStrs.length());
                }

                final String finalFwnrStrs = fwnrStrs, finalFwnrNameStrs = fwnrNameStrs;
                Validate.check(con, new IValidateResult() {
                    @Override
                    public void onValidateSuccess() {
                        //Toast.makeText(con, "验证成功", Toast.LENGTH_SHORT).show();
                        saveData(finalFwnrStrs, finalFwnrNameStrs);
                    }

                    @Override
                    public void onValidateError(String msg, View view) {
                        view.setFocusable(true);
                        //Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
                        SweetAlertDialogUtil.WarningDialog(con, "提示", msg);
                    }

                    @Override
                    public Animation onValidateErrorAnno() {
//                        return ValidateAnimation.horizontalTranslate();
                        return null;
                    }
                });
            }
        });
    }

    @Override
    protected void initData() {

    }
    @Override
    protected void initListener() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Validate.unreg(this);
    }

    private void saveData(String finalFwnrStrs, String finalFwnrNameStrs){
        //保存
        if(null == finalFwnrStrs || "".equals(finalFwnrStrs)){
            SweetAlertDialogUtil.WarningDialog(con, "提示", "请选择服务内容");
        } else {
            if (obj == null)
                obj = new ServicePlan();

            obj.setService_content(finalFwnrStrs);
            obj.setService_content_name(finalFwnrNameStrs);
            obj.setService_content_qt(fwnr_qt.getText().toString());
            obj.setPlan_time(jhsj.getText().toString());
            obj.setRemarks(bz.getText().toString());
            if (NetWorkUtils.isNetworkConnected(con)) {
                RequestParams ps = new RequestParams();
                ps.add("entity.sign_up_id", signupid);
                ps.add("entity.plan_time", obj.getPlan_time());
                ps.add("entity.service_content", obj.getService_content());
                ps.add("entity.remarks", obj.getRemarks());
                ps.add("entity.service_content_qt", obj.getService_content_qt());
                ps.add("entity.service_content_name", obj.getService_content_name());
                if (getIntent().getStringExtra("type").equals("edit"))
                    ps.add("entity.id", obj.getSpid());
                ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                ps.add("type", "2");
                UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        String content = new String(response);
                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                        if (ret.getCode().equals("200")) {
                            MyToastUtil.ShowToast(con, "成功");
                        }else{
                            MyToastUtil.ShowToast(con, ret.getInfo());
                        }
                        finish();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                        MyToastUtil.ShowToast(con, "失败");
                    }
                });
            }
        }
    }
}
